package com.hzlx.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.io.IOException;

import com.hzlx.ResultDto;
import com.hzlx.WorkOrderDto;
import com.hzlx.service.SimpleMessageListener;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.hzlx.domain.MesWorkOrders;
import com.hzlx.service.IMesWorkOrdersService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 工单管理Controller
 * 
 * @author ruoyi
 * @date 2025-06-30
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class MesWorkOrdersController extends BaseController
{
    @Autowired
    SimpleMessageListener simpleMessageListener;
    @Autowired
    private IMesWorkOrdersService mesWorkOrdersService;

    /**
     * 查询工单管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MesWorkOrders mesWorkOrders)
    {
        startPage();
        List<MesWorkOrders> list = mesWorkOrdersService.selectMesWorkOrdersList(mesWorkOrders);
        return getDataTable(list);
    }

    /**
     * 导出工单管理列表
     */
    @RequiresPermissions("workorder-service:orders:export")
    @Log(title = "工单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MesWorkOrders mesWorkOrders)
    {
        List<MesWorkOrders> list = mesWorkOrdersService.selectMesWorkOrdersList(mesWorkOrders);
        ExcelUtil<MesWorkOrders> util = new ExcelUtil<MesWorkOrders>(MesWorkOrders.class);
        util.exportExcel(response, list, "工单管理数据");
    }

    /**
     * 获取工单管理详细信息
     */
    @RequiresPermissions("workorder-service:orders:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(mesWorkOrdersService.selectMesWorkOrdersById(id));
    }

    /**
     * 新增工单管理
     */
    @RequiresPermissions("workorder-service:orders:add")
    @Log(title = "工单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultDto<String> add(@RequestBody MesWorkOrders mesWorkOrders) {
        String orderNumber = generateOrderNumber();
        mesWorkOrders.setOrderNumber(orderNumber);
        return mesWorkOrdersService.insertMesWorkOrders(mesWorkOrders);
    }

    // 静态计数器和日期
    private static int counter = 0;
    private static LocalDate currentDate = LocalDate.now();
    private static final Object lock = new Object();

    private String generateOrderNumber() {
        synchronized (lock) {
            LocalDate today = LocalDate.now();

            // 如果日期变更，重置计数器
            if (!today.isEqual(currentDate)) {
                currentDate = today;
                counter = 0;
            }

            counter++;

            int year = today.getYear();
            int month = today.getMonthValue();
            int day = today.getDayOfMonth();

            // 格式化三位数序列号
            String serialNumber = String.format("%03d", counter);

            return "WO" + year + String.format("%02d", month) + String.format("%02d", day) + serialNumber;
        }
    }

    /**
     * 修改工单管理
     */
    @RequiresPermissions("workorder-service:orders:edit")
    @Log(title = "工单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MesWorkOrders mesWorkOrders)
    {
        return toAjax(mesWorkOrdersService.updateMesWorkOrders(mesWorkOrders));
    }

    /**
     * 删除工单管理
     */
    @RequiresPermissions("workorder-service:orders:remove")
    @Log(title = "工单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mesWorkOrdersService.deleteMesWorkOrdersByIds(ids));
    }

    @GetMapping("/byProductId/{productId}")
    public List<WorkOrderDto> getInfoDto(@PathVariable Long productId){
        List<WorkOrderDto> list = mesWorkOrdersService.selectMesWorkOrdersByProductId(productId);
        log.info("Controller返回值类型: {}", list.getClass().getName());
        return list;
    }

    @PutMapping("/workOrderDto")
    public void editByMaterial(@RequestBody WorkOrderDto workOrderDto){
        mesWorkOrdersService.updateMesWorkOrdersByMaterial(workOrderDto);
    }
}
